import os
import re
import json

import webapp2

import settings

def json_response(request, path=None):
  data_path = settings.DATA_DIR

  if path:
    data_path = os.path.join(data_path, path)

  json_dict = collect_data(data_path)

  response = webapp2.Response()
  response.headers['Content-Type'] = 'application/json'
  response.out.write(json.dumps(json_dict))
  return response

def collect_data(path):
  json_dict = {}

  if os.path.isdir(path):
    file_list = os.listdir(path)

    # Make sure there are files in the directory
    if file_list:
      for f in file_list:
        file_path = os.path.join(path, f)
        if os.path.isdir(file_path):
          json_dict[f] = collect_data(file_path)
        elif f.endswith('.json'):
          json_dict.update(create_json_dict(file_path))

  elif path.endswith('.json') and os.path.exists(path):
    json_dict = create_json_dict(path)

  return json_dict

def create_json_dict(path):
  key = re.search('/([\w-]+).json$', path).groups()[0]
  value = parse_json_file(path)
  return {key:value}

def parse_json_file(path):
  file_string = open(path).read()
  return json.loads(file_string)
